<!DOCTYPE html>
{% autoescape true %}
<html>
  <head>
    <!-- [START css] -->
    <link type="text/css" rel="stylesheet" href="/bootstrap/css/bootstrap.css">
    <link type="text/css" rel="stylesheet" href="/bootstrap/css/bootstrap-responsive.css">
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAGY2fazCRYroMUe2jgDZLLVS_Texl6ztE&callback&callback=initMap&libraries=&v=weekly"
      defer
    ></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>

    <!-- [END css] -->
    <style type="text/css">
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }

      /* Optional: Makes the sample page fill the window. */
      html,
      body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <script type="text/javascript">
	    let map;
      var directionsService;
      var directionsRenderer;
      var currlatlng;
      var markersArray=[]
      const destinationIcon =
          "https://chart.googleapis.com/chart?" +
          "chst=d_map_pin_letter&chld=D|FF0000|000000";
        const originIcon =
          "https://chart.googleapis.com/chart?" +
          "chst=d_map_pin_letter&chld=O|FFFF00|000000";

      function initMap() {
        directionsService = new google.maps.DirectionsService();
        directionsRenderer = new google.maps.DirectionsRenderer();
        map = new google.maps.Map(document.getElementById("map"), {
          center: { lat: -34.397, lng: 150.644 },
          zoom: 8,
        });
       directionsRenderer.setMap(map);
      }
      // 获取前前位置
      function initLocation(){
         getplace()
    	  if (navigator.geolocation) {
    	        //获取当前地理位置
    	        navigator.geolocation.getCurrentPosition(function (position) {
    	            var coords = position.coords;
    	            // currlatlng = { lat: coords.latitude, lng: coords.longitude };
    	            currlatlng = { lat: -37.81121976663945, lng: 144.96917542262287 ,title:'My location',description:''}
    	            //console.log(position);
    	            showMaps(currlatlng,true,0);
    	        },
    	        function (error) {
    	            //处理错误
    	            switch (error.code) {
    	               case 1:
    	                   alert("位置服务被拒绝。");
    	                   break;
    	            case 2:
    	                   alert("暂时获取不到位置信息。");
    	                   break;
    	            case 3:
    	                alert("获取信息超时。");
    	                break;
    	            default:
    	                alert("未知错误。");
    	                break;
    	            }
    	        });
    	    } else {
    	        alert("你的浏览器不支持HTML5来获取地理位置信息。");
    	    }
      }
       function dh(lat,lnt){
    	  var target = { lat: lat, lng: lnt}
    	  calculateAndDisplayRoute(currlatlng,target)
      }
      function showMaps(data, ismark, type){
    	    //指定一个google地图上的坐标点，同时指定该坐标点的横坐标和纵坐标
    	    var latlng = new google.maps.LatLng(data.lat, data.lng);
    	    var myOptions = {
    	        zoom: 14, //设定放大倍数
    	        center: latlng, //将地图中心点设定为指定的坐标点
    	        mapTypeId: google.maps.MapTypeId.ROADMAP //指定地图类型
    	    };
    	    //创建地图，并在页面map中显示
//     	    var map = new google.maps.Map(document.getElementById("map"), myOptions);
    	    map.setCenter(latlng, 14);
    	    //在地图上创建标记
    	    var marker = new google.maps.Marker({
    	        position: latlng, //将前面设定的坐标标注出来
    	        map: map //将该标注设置在刚才创建的map中
    	    });
    	    if(ismark){
    	    	 //标注提示窗口
                var infoWindow = new google.maps.InfoWindow({
                    content: "<div style = 'width:200px;min-height:40px'><div>" + data.title + "</div><button  class='btn' onclick='dh("+data.lat+","+data.lng+")'>Navigation</button><div>" + data.description + "</div></div>"
                });
                //打开提示窗口
                infoWindow.open(map, marker);
    	    }
           var infoWindow = new google.maps.InfoWindow();
           //Attach click event to the marker.
           (function (marker, data) {
               google.maps.event.addListener(marker, "click", function (e) {
                   //Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
                    var content = "<div style = 'width:200px;min-height:40px'><div>" + data.title + "</div><button  class='btn' onclick='dh("+data.lat+","+data.lng+")'>Navigation</button><div>" + data.description + "</div></div>";
            	   if(type==0){
                       // 我的位置
                        var content = "<div style = 'width:200px;min-height:40px'><div>" + data.title + "</div><div>" + data.description + "</div></div>"
                   } else if(type==1){
                       // shared Bicycle
                        var content = "<div style = 'width:200px;min-height:40px'><div>shared Bicycle</div><button  class='btn' onclick='dh("+data.lat+","+data.lng+")'>Navigation</button><div>" + data.description + "</div></div>"
                   } else if(type==2){
//                        // 单车线路
//                         var content = "<div style = 'width:200px;min-height:40px'><div>" + data.title + "</div><div onclick='dh("+data.lat+","+data.lng+")'>Navigation</div><div>" + data.description + "</div></div>"
                   }else if(type==3){
//                        // 日活动
//                         var content = "<div style = 'width:200px;min-height:40px'><div>" + data.title + "</div><div onclick='dh("+data.lat+","+data.lng+")'>Navigation</div><div>" + data.description + "</div></div>"
                   }else if(type==4){
                       // public toilet
                        var content = "<div style = 'width:200px;min-height:40px'><div>public toilet</div><button  class='btn' onclick='dh("+data.lat+","+data.lng+")'>Navigation</button><div>" + data.description + "</div></div>"
                   }else if(type==5){
                       // Public BBQ place地点
                        var content = "<div style = 'width:200px;min-height:40px'><div>Public BBQ place</div><button  class='btn' onclick='dh("+data.lat+","+data.lng+")'>Navigation</button><div>" + data.description + "</div></div>"
                   }
                    
                   infoWindow.setContent(content);
                   infoWindow.open(map, marker);
               });
           })(marker, data);

    	}
        function search(){
    		var address = $('#addr').val();
//     	    address=encodeURIComponent(address)
    	    var geocoder = new google.maps.Geocoder();
    	    geocoder.geocode( { 'address': address}, function(results, status) {
    	          if (status == google.maps.GeocoderStatus.OK) {
//     	        	  alert('地理解析结果：'+results[0].formatted_address);
                      //geometry是一个包含bounds（界限），location（纬度/经度坐标）,location_type和viewport（视图范围）
                      //获取解析后的经纬度
//                         alert('地理解析结果：'+results[0].formatted_address);
                        var coords={
                        		title:'搜索',
                        		lat : results[0].geometry.location.lat(),
                        		lng : results[0].geometry.location.lng(),
                        		name : results[0].formatted_address,
                        		description : results[0].formatted_address
                        }
                        showMaps(coords,true);
    	          } else {
    	            alert("Geocode was not successful for the following reason: " + status);
    	          }
    	        });
//     	    geocoder.geocode({address:'1600+Amphitheatre+Parkway,+Mountain+View,+CA'},function geoResults(results, status){
//     	          //这里是回掉函数(即结果处理函数)
//     	          //状态为Ok说明有结果
//     	          if (status == google.maps.GeocoderStatus.OK) {
//     	              //一般情况下会有多个结果
//     	              //第一个结果为最佳匹配的结果（匹配地名最全的结果），这里只去第一个，其他的可以根据需要自己循环出来
//     	              //格式化过后的地址
//     	              alert('地理解析结果：'+results[0].formatted_address);
//     	              //geometry是一个包含bounds（界限），location（纬度/经度坐标）,location_type和viewport（视图范围）
//     	              //获取解析后的经纬度
//     	                alert('地理解析结果：'+results[0].geometry.location);
//     	          }else{
//     	            alert("：error " + status);
//     	          }
//     	        });
    	}
    	function showplace(address){
    	    var geocoder = new google.maps.Geocoder();
    	    geocoder.geocode( { 'address': address}, function(results, status) {
    	          if (status == google.maps.GeocoderStatus.OK) {
//     	        	  alert('地理解析结果：'+results[0].formatted_address);
                      //geometry是一个包含bounds（界限），location（纬度/经度坐标）,location_type和viewport（视图范围）
                      //获取解析后的经纬度
//                         alert('地理解析结果：'+results[0].formatted_address);
                        var coords={
                        		latitude:results[0].geometry.location.lat(),
                        		longitude:results[0].geometry.location.lng(),
                        		name:results[0].formatted_address
                        }
                        showMaps(coords);
                        uploadAddr(address);
    	          } else {
    	            alert("Geocode was not successful for the following reason: " + status);
    	          }
    	        });
//     	    geocoder.geocode({address:'1600+Amphitheatre+Parkway,+Mountain+View,+CA'},function geoResults(results, status){
//     	          //这里是回掉函数(即结果处理函数)
//     	          //状态为Ok说明有结果
//     	          if (status == google.maps.GeocoderStatus.OK) {
//     	              //一般情况下会有多个结果
//     	              //第一个结果为最佳匹配的结果（匹配地名最全的结果），这里只去第一个，其他的可以根据需要自己循环出来
//     	              //格式化过后的地址
//     	              alert('地理解析结果：'+results[0].formatted_address);
//     	              //geometry是一个包含bounds（界限），location（纬度/经度坐标）,location_type和viewport（视图范围）
//     	              //获取解析后的经纬度
//     	                alert('地理解析结果：'+results[0].geometry.location);
//     	          }else{
//     	            alert("：error " + status);
//     	          }
//     	        });
    	}
    	function deleteMarkers(markersArray) {
          for (let i = 0; i < markersArray.length; i++) {
            markersArray[i].setMap(null);
          }
          markersArray = [];
        }
        function navigation(){
    	  var target = $('#addr').val()
    	  if(target==''){
    		  alert('请输入地址')
    		  return;
    	  }
    	  calculateAndDisplayRoute(currlatlng,target)
        }
        function calculateAndDisplayRoute(currlatlng,target) {
    	  var request = {
    		        origin: currlatlng,
    		        destination: target,
    		        travelMode: 'DRIVING'
    		    };
          directionsService.route(
        		  request,
            (response, status) => {
              if (status === "OK") {
                directionsRenderer.setDirections(response);

                const geocoder = new google.maps.Geocoder();
                var service = new google.maps.DistanceMatrixService();
                service.getDistanceMatrix(
                        {
                          origins: [currlatlng],
                          destinations: [target],
                          travelMode: google.maps.TravelMode.DRIVING,
                          unitSystem: google.maps.UnitSystem.METRIC,
                          avoidHighways: false,
                          avoidTolls: false,
                        },
                        (response, status) => {
                          if (status !== "OK") {
                            alert("Error was: " + status);
                          } else {
                            const originList = response.originAddresses;
                            const destinationList = response.destinationAddresses;
                            const outputDiv = document.getElementById("output");
                            outputDiv.innerHTML = "";
                            deleteMarkers(markersArray);

                            const showGeocodedAddressOnMap = function (asDestination) {
                              const icon = asDestination ? destinationIcon : originIcon;

                              return function (results, status) {
                                if (status === "OK") {
                                    var bounds = new google.maps.LatLngBounds();
                                  map.fitBounds(bounds.extend(results[0].geometry.location));
                                  markersArray.push(
                                    new google.maps.Marker({
                                      map,
                                      position: results[0].geometry.location,
                                      icon: icon,
                                    })
                                  );
                                } else {
                                  alert("Geocode was not successful due to: " + status);
                                }
                              };
                            };

                            for (let i = 0; i < originList.length; i++) {
                              const results = response.rows[i].elements;
                              /*geocoder.geocode(
                                { address: originList[i] },
                                showGeocodedAddressOnMap(false)
                              );*/

                              for (let j = 0; j < results.length; j++) {
                                /*geocoder.geocode(
                                  { address: destinationList[j] },
                                  showGeocodedAddressOnMap(true)
                                );*/
                                outputDiv.innerHTML +=
                                  originList[i] +
                                  " to " +
                                  destinationList[j] +
                                  ": " +
                                  results[j].distance.text +
                                  " in " +
                                  results[j].duration.text +
                                  "<br>";
                              }
                            }
                          }
                        }
                      );

              } else {
                window.alert("Directions request failed due to " + status);
              }
            }
          );
        }
    	function check(){
    	   var id = document.getElementById('id').value
    	   if(id==''){
    	     document.getElementById('msg').innerHTML='Id can not be blank'
    	     return false
           }
    	   var password = document.getElementById('password').value
    	   if(password==''){
    	     document.getElementById('msg').innerHTML='Password can not be blank'
    	     return false
           }
          return true
	    }

	    function uploadAddr(searchText){
          var id=$('#id').val();
          var isgoogle = $('#isgoogle').val()
          if(isgoogle==1){
            id = $('#googleId').val();
          }
          if(id == undefined || id == ''){
            return;
          }
          var url = 'addSearch?userid='+id+'&searchText='+searchText
          $.ajax({
            url:url, //请求的服务端地址
            type:"get",
            success:function(data){
                console.info('upload success')
                getplace();
            },
            error:function(jqXHR, textStatus,responseText, errorThrown){
                console.info('upload fail')
                getplace()
            }
          });
        }

        function getplace(){
            var id=$('#id').val();
            var isgoogle = $('#isgoogle').val()
            if(isgoogle==1){
              id = $('#googleId').val();
            }
            if(id == undefined || id == ''){
              return;
            }
            var url = 'getPlace?id='+id
            $.ajax({
              url:url, //请求的服务端地址
              type  :"get",
              success:function(data){
                var html = ' <span>Search History:</span>'

                  if(data){
                    var dataobj = eval(data)

                     for(var i=0;i<dataobj.length;i++){
                        var ap = '<a style="margin-right: 10px; margin-left: 10px;cursor: pointer"" onclick="showplace(\''+dataobj[i].searchText+'\')">'+dataobj[i].searchText+'</a>';
                        html = html + ap;
                     }
                  }
                  $('#placeDiv').html(html)
              },
              error:function(jqXHR, textStatus,responseText, errorThrown){
                  console.info('getPlace fail')
              }
            });
        }

        function amap(url,type){
    		$.ajax({
                url:url, //请求的服务端地址
                type:"get",
                success:function(data){
                    for(var i=0;i<data.length;i++){
                        var o = data[i];
                        var coords={
                        		title : '',
                        		lat : o.lat,
                        		lng : o.lon,
                        		description : ''
                        }
                        console.log(coords)
                        showMaps(coords,false,type);
                    }

                },
                error:function(jqXHR, textStatus,responseText, errorThrown){
                    console.info('share fail')
                }
              });
    	}
    	function barbecuemap(url){
            $.ajax({
                url:url, //请求的服务端地址
                type:"get",
                success:function(data){
                    for(var i=0;i<data.length;i++){
                        var o = data[i];
                        var coords={
                        		title : '',
                        		lat : o.geom.latitude,
                                lng : o.geom.longitude,
                                description:''
                        }
                        console.log(coords)
                        showMaps(coords,false,5);
                    }

                },
                error:function(jqXHR, textStatus,responseText, errorThrown){
                    console.info('share fail')
                }
              });
        }

    	// 单车线路
    	function pline(){
    		$.ajax({
                url:'https://data.melbourne.vic.gov.au/resource/hmuz-nz6m.json', //请求的服务端地址
                type:"get",
                success:function(data){
                    for(var i=0;i<data.length;i++){
                        var o = data[i];
                        var tg =o.the_geom
                        var type = tg.type
                        if('MultiLineString'!=type){
                        	continue;
                        }
                        var c = tg.coordinates[0]
                        var flightPlanCoordinates = []
                        for(var j=0;j<c.length;j++){
                        	flightPlanCoordinates.push({lat:c[j][1],lng:c[j][0]})
                        }
                           const flightPath = new google.maps.Polyline({
                             path: flightPlanCoordinates,
                             geodesic: true,
                             strokeColor: "#FF0000",
                             strokeOpacity: 1.0,
                             strokeWeight: 2,
                           });
                           flightPath.setMap(map);
                    }

                },
                error:function(jqXHR, textStatus,responseText, errorThrown){
                    console.info('share fail')
                }
              });
    	}
    	// 日活动
    	function eara(){
            $.ajax({
                url:'https://data.melbourne.vic.gov.au/resource/txcy-uafv.json', //请求的服务端地址
                type:"get",
                success:function(data){
                    for(var i=0;i<data.length;i++){
                        var o = data[i];
                        var tg =o.the_geom
                        var type = tg.type
                        if('MultiPolygon'!=type){
                            continue;
                        }

                        var bounds = new google.maps.LatLngBounds();

                        var c = tg.coordinates[0]
                        var flightPlanCoordinates = []
                        var bounds = new google.maps.LatLngBounds();

                        for(var j=0;j<c[0].length;j++){
                        	marker = new google.maps.Marker({
                                position: new google.maps.LatLng(c[0][j][1], c[0][j][0]),
                                map: map
                              });
                        	 var lat = c[0][j][1]
                        	 var lnt = c[0][j][0]
                              google.maps.event.addListener(marker, 'click', (function(marker, i) {
                                return function() {
                               	var infoWindow = new google.maps.InfoWindow({
                                       content: "节假日<br/>节日："+(o.notes==undefined?'':o.notes)+"<br/>开始："+o.start_date+"<br/>结束："+o.end_date +"<br/><button  class='btn' onclick='dh("+lat+","+lnt+")'>Navigation</button>"//提示窗体内的提示信息
                                   });
                               	infoWindow.open(map, marker);
                                }
                              })(marker, i));


                            var latlng = new google.maps.LatLng(c[0][j][1], c[0][j][0]);
                            flightPlanCoordinates.push(latlng)
                            bounds.extend(latlng);
                        }

                        var poly = new google.maps.Polygon({
                            paths: flightPlanCoordinates,
                            strokeColor: 'green',
                            strokeOpacity: 0.8,
                            strokeWeight: 3,
                            fillColor: '#FF0000',
                            fillOpacity: 0.1
                        });
                        poly.setMap(map);


                        map.fitBounds(bounds);
                        break;
                    }
                },
                error:function(jqXHR, textStatus,responseText, errorThrown){
                    console.info('share fail')
                }
              });
        }
    	// shared Bicycle
    	function share(){
    		amap('https://data.melbourne.vic.gov.au/resource/vrwc-rwgm.json', 1)
    	}
    	// 公共厕
    	function toilet(){
    		amap('https://data.melbourne.vic.gov.au/resource/ru3z-44we.json',4)
        }

    	function findPlace(tag){
            initMap();
    		if(tag==0){
                // 我的位置
                initLocation()
            } else if(tag==1){
    			// shared Bicycle
    			share()
    		} else if(tag==2){
    			// 单车线路
    			pline()
            }else if(tag==3){
            	// 日活动
            	eara()
            }else if(tag==4){
            	// public toilet
            	toilet();
            }else if(tag==5){
            	// Public BBQ place地点
            	barbecuemap('https://data.melbourne.vic.gov.au/resource/5nb5-w7hq.json');
            }
    	}
    	function init(){
    		initLocation();
//     		share();
//     		toilet();
//     		barbecuemap();
//     		pline();
//     		eara();

    	}
    </script>
  </head>
    <body onload="init()">
    {% if user %}
      {% if isgoogle == 1 %}
        <div style="margin-left: 15px;margin-top: 10px">[{{ user }}]<a style="padding-left: 10px;"  class="btn" href="loginOut"><a href="{{ url|safe }}" class="btn">{{ url_linktext }}</a></a></div>
        <input type="hidden" id="googleId" value="{{user.user_id()}}" />
         <input type="hidden" id="isgoogle" value="{{isgoogle}}" />
      {% endif %}
      {% if isgoogle != 1 %}
        <div style="margin-left: 15px;margin-top: 10px">[{{user.name}}]<a style="padding-left: 10px;"  class="btn" href="loginOut">退出</a></div>
      {% endif %}

      <input type="hidden" id="id" value="{{id}}">
      <div style="margin-bottom: 5px;margin-left: 15px;margin-top: 10px" id="placeDiv"></div>
      {% else %}
      <form action="/login" method="post" style="margin:0 0 0px" onsubmit="return check()">
        <div style="margin-top: 10px;margin-left: 10px;">
            <input type="text" name="id" id="id" placeholder="id">
            <input type="password" name="password" id="password" placeholder="password">
            <input type="submit" style="margin-top: -10px;" class="btn" value="Login">
            <a href="{{ url|safe }}" style="float: right; margin-right: 20px;" class="btn">{{ url_linktext }}</a>
            <span id="msg" style="color: red;font-size: 20px;padding-left: 10px">{{msg}}</span>
        </div>
    </form>
    {% endif %}

    <div style="margin-bottom: 5px;margin-left: 10px;">
        <input type="text" id="addr"> 
        <button style="margin-top: -10px;"  class="btn" onclick="search()">search</button> 
        <button  class="btn" style="margin-top: -10px; margin-left: 10px;"  onclick="navigation()">Navigation</button>
        <span style="color: red;margin-left: 10px;" id="output"></span>
        <span style="font-size: 30px;padding-right: 20px;float: right;margin-top: 10px;">The Convenient Mel</span>
    </div>
    <div>
        <button onclick="findPlace(0)" class="btn">My location</button>
        <button onclick="findPlace(1)" class="btn">Shared Bicycle</button>
        <button onclick="findPlace(2)" class="btn">Bike routes</button>
        <button onclick="findPlace(3)" class="btn">City Events</button>
        <button onclick="findPlace(4)" class="btn">Public Toilets</button>
        <button onclick="findPlace(5)" class="btn">Public BBQ places</button>
    </div>
    <div id="map"></div>
  </body>
</html>
{% endautoescape %}
